package com.bluexmicro.example.page.pick.peripheral

import android.bluetooth.BluetoothDevice
import android.util.Log
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.material.Icon
import androidx.compose.material.IconButton
import androidx.compose.material3.*
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavHostController
import com.bluexmicro.example.R
import com.bluexmicro.example.dataStore
import com.bluexmicro.example.page.pick.peripheral.condition.ConditionView
import com.bluexmicro.example.page.pick.peripheral.scan.PeripheralListView
import com.google.accompanist.insets.ui.TopAppBar

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun PeripheralPage(
    navHostController: NavHostController,
    onSelectedListener: (device: BluetoothDevice) -> Unit
) {

    val context = LocalContext.current
    val viewModel = viewModel<PeripheralViewModel>(factory = PeripheralVMFactory(context.dataStore))
    LaunchedEffect(Unit) {
        viewModel.loadFilterElements()
    }
    var keyRemember by remember {
        viewModel.displayKey
    }
    var rssiRemember by remember {
        viewModel.displayRssi
    }
    var connectableRemember by remember {
        viewModel.displayConnectable
    }
    var showFilterRemember by remember {
        viewModel.displayFilter
    }
    Scaffold(
        topBar = {
            PeripheralTopBar(onClose = { navHostController.popBackStack() })
        }
    ) {
        Column(
            modifier = Modifier.fillMaxSize()
        ) {
            PeripheralFilter(rssiRemember, keyRemember, connectableRemember) {
                showFilterRemember = !showFilterRemember
            }
            if (showFilterRemember) {
                ScanFilterComposable(
                    rssiRemember,
                    keyRemember,
                    connectableRemember,
                    onSave = { rssi, key, connectable ->
                        rssiRemember = rssi.toFloat()
                        keyRemember = key
                        connectableRemember = connectable
                        viewModel.save()
                        showFilterRemember = false
                    },
                    onCancel = { showFilterRemember = false }
                )
            } else {
                ConditionView {
                    PeripheralListView(
                        peripheralViewModel = viewModel,
                        onSelectedListener = onSelectedListener
                    )
                }
            }
        }
    }
}

@Composable
fun PeripheralTopBar(onClose: () -> Unit) {
    TopAppBar(title = {
        Text("选择设备", color = MaterialTheme.colorScheme.onPrimary)
    }, navigationIcon = {
        IconButton(
            onClick = onClose,
        ) {
            Icon(
                painter = painterResource(R.drawable.ic_arrow_left),
                null,
                modifier = Modifier.size(24.dp),
                tint = MaterialTheme.colorScheme.onPrimary
            )
        }
    }, backgroundColor = MaterialTheme.colorScheme.primary)
}

@Composable
fun PeripheralFilter(
    rssi: Float,
    keyFilter: String,
    connectable: Boolean,
    onFilterTap: () -> Unit
) {
    Row(
        modifier = Modifier.fillMaxWidth()
            .padding(16.dp)
            .background(Color.LightGray)
            .clickable {
                onFilterTap.invoke()
            }.padding(12.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        LazyRow(modifier = Modifier.weight(1f)) {
            item {
                if (keyFilter.isNotBlank()) {
                    FilterDisplayItem(keyFilter)
                }
                FilterDisplayItem("${rssi.toInt()}dbm")
//                if (connectable) {
//                    Spacer(modifier = Modifier.width(4.dp))
//                    FilterDisplayItem("Connectable Only")
//                }
            }
        }
        Icon(
            painter = painterResource(R.drawable.ic_filiter),
            null,
            modifier = Modifier.size(24.dp),
            tint = MaterialTheme.colorScheme.onPrimary
        )
    }
}

@Composable
fun FilterDisplayItem(tagName: String) {
    Text(
        tagName,
        color = MaterialTheme.colorScheme.onPrimary,
        style = MaterialTheme.typography.labelSmall,
        modifier = Modifier.padding(end = 4.dp).background(
            MaterialTheme.colorScheme.secondary,
            shape = RoundedCornerShape(24.dp)
        ).padding(8.dp)
    )
}

@Composable
fun ScanFilterComposable(
    rssiThreshold: Float, keyFilter: String, connectable: Boolean,
    onSave: (rssi: Int, key: String, connectable: Boolean) -> Unit,
    onCancel: () -> Unit
) {
    var rssiRemember by remember {
        //-127 ~ 0
        mutableStateOf(rssiThreshold)
    }
    var connectableRemember by remember {
        mutableStateOf(connectable)
    }
    var keyRemember by remember {
        mutableStateOf(keyFilter)
    }
    Column(
        modifier = Modifier.fillMaxWidth().padding(start = 16.dp, end = 16.dp, bottom = 16.dp)
    ) {
        Spacer(modifier = Modifier.height(16.dp))
        OutlinedTextField(keyRemember,
            modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),
            shape = RoundedCornerShape(8.dp),
            label = {
                Text("以名字或者地址进行过滤", color = Color.LightGray)
            },
            onValueChange = {
                keyRemember = it
            })
        Spacer(modifier = Modifier.height(16.dp))
        Text(
            "Rssi : ${rssiRemember.toInt()}dbm",
            style = MaterialTheme.typography.labelSmall,
            modifier = Modifier.padding(horizontal = 16.dp)
        )
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Spacer(modifier = Modifier.width(16.dp))
            Text("-127dbm", fontSize = 10.sp)
            Spacer(modifier = Modifier.width(8.dp))
            Slider(
                rssiRemember + 127,
                onValueChange = {
                    rssiRemember = it - 127
                },
                valueRange = 0f..127f, //-127~0
                modifier = Modifier.weight(1f),
            )
            Spacer(modifier = Modifier.width(8.dp))
            Text("0dbm", fontSize = 10.sp)
            Spacer(modifier = Modifier.width(16.dp))
        }
//        Row(
//            verticalAlignment = Alignment.CenterVertically
//        ) {
//            Checkbox(connectableRemember, onCheckedChange = {
//                connectableRemember = it
//            })
//            Text("Show only connectable devices")
//        }
        Button(onClick = {
            onSave.invoke(rssiRemember.toInt(), keyRemember, connectableRemember)
        }, modifier = Modifier.fillMaxWidth().padding(16.dp)) {
            Text("保存", fontSize = 18.sp)
        }
        TextButton(onClick = {
            onCancel.invoke()
        }, modifier = Modifier.align(Alignment.CenterHorizontally)) {
            Text("取消")
        }
    }
}


